
import SnapKit
import UIKit

class BLAVplayerTool : UIView {
    
    // 单例对象
    static let shareInstance: BLAVplayerTool = BLAVplayerTool()
    
    /* 播放器 */
    var player : AVPlayer? = nil
    var playerItem : AVPlayerItem = AVPlayerItem(URL: NSURL(string: "")!)
    // 播放器的Layer
    var playerLayer = AVPlayerLayer()
    /* 定时器, 用作更新播放进度 */
    var progressTimer = NSTimer()
    /* 播放器承载View */
    var displayView = UIView()
    
    var isPlay : Bool = false
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


//设置控制界面UI
extension BLAVplayerTool{
    
    ///设置播放
    func setupDisplayUI() {
        player = AVPlayer(playerItem: playerItem)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.bounds
        displayView.layer.addSublayer(playerLayer)
        self.addSubview(displayView)
        displayView.snp_makeConstraints(closure: { (make) in
            make.top.left.bottom.right.equalToSuperview()

        })
    }
    ///设置控制界面
    func setupControlUI() {
        
    }
}


// MARK: - 设置播放的视频
extension BLAVplayerTool{
 
    
    func setPlayItem(urlStr : String) {
        let url = NSURL(string: urlStr)
        playerItem = AVPlayerItem(URL: url!)
        
        if player == nil {
            //设置播放界面
            setupDisplayUI()
            
            //设置控制界面
            setupControlUI()
        }
        else{
            player!.replaceCurrentItemWithPlayerItem(playerItem)
            
        }
        player!.play()
        isPlay = true
        
    }
}
